window.addEventListener("load", function() { rememberExtension.init(); }, false);

// Create an array of sites that can be pushed to sortAndDisplay
function makeTheseSites(uri, first, last, count, theseSites) {
  var justnow = Date.now();

// Only display if has more then one visit or is over 7 days old
  if (count != 1 && first < (justnow - 604800)) {
    var average = (last - first) / count;
    var sincelast = justnow - last;
    var rank = (sincelast / average) * 1000;
    
    rank = Math.round(rank);
    
    // THIS REALLY SUCKS!
    if (rank < 10) {
      rank = "0000000" + rank;
    } else if (rank < 100) {
      rank = "000000" + rank;
    } else if (rank < 1000) {
      rank = "00000" + rank;
    } else if (rank < 10000) {
      rank = "0000" + rank;
    } else if (rank < 100000) {
      rank = "000" + rank;
    } else if (rank < 1000000) {
      rank = "00" + rank;
    } else if (rank < 10000000) {
      rank = "0" + rank;
    }
    var currently = new Array(rank, uri, count);
    theseSites.push(currently);
  }
  return theseSites;
}

// Expects an array of sites, used in doVooDoo() to display everything
function sortAndDisplay(theseSites) {
  theseSites = theseSites.sort();
  theseSites = theseSites.reverse();
  
  var everything = "<table border='1' width='100%'><tr><td>Rank</td><td>Visits</td><td>URL</td></tr>\n";
  
  for (var key in theseSites) {
    everything = everything + "<tr><td><b>" + theseSites[key][0] + "</b></td><td>"+ theseSites[key][2] + "</td><td><a href='" + theseSites[key][1] + "'>" + theseSites[key][1] + "</a></td></tr>\n";
  }
  
  everything = everything + "</table>";
 
  var savefile = Components.classes["@mozilla.org/file/directory_service;1"]
    .getService(Components.interfaces.nsIProperties)
    .get("ProfD", Components.interfaces.nsIFile);
  savefile.append("remembertosurf.html");
  
  var foStream = Components.classes["@mozilla.org/network/file-output-stream;1"]
    .createInstance(Components.interfaces.nsIFileOutputStream);
  foStream.init(savefile, 0x02 | 0x08 | 0x20, 0777, 0);
  foStream.write(everything, everything.length);
  foStream.close();

  getBrowser().loadURI(savefile.path);
}